package 链表实现队列;

import java.util.Iterator;

public class Queue<E> implements Iterable<E>{

    @Override
    public Iterator<E> iterator() {
        return new Iterator<>() {
            Node<E> p = head.next;

            @Override
            public boolean hasNext() {
                return p != head;
            }

            @Override
            public E next() {
                E value = p.value;
                p = p.next;
                return value;
            }
        };
    }

    public static class Node<E> {
        E value;
        Node<E> next;

        public Node(E value, Node<E> next) {
            this.value = value;
            this.next = next;
        }
    }

    Node<E> head = new Node<>(null,null);
    Node<E> tail = head;
    private int size; // 节点数
    private int capacity = Integer.MAX_VALUE; // 容量

    public Queue(int capacity) {
        this.capacity = capacity;
        head.next = tail;
    }

    public Queue() {
        head.next = tail;
    }






    /**
     * 向队列尾插入值
     * @param value 待插入值
     * @return 插入成功返回true,插入失败返回false
     */
    public boolean offer(E value) {
        if (isFull()) {
            return false;
        }
        Node<E> added = new Node<>(value, head);
        tail.next = added;
        tail = added;
        size++;
        return true;
    }

    /**
     * 从队列头获取值, 并移除
     * @return 如果队列非空返回对头值, 否则返回null
     */
    public E poll() {
        if (isEmpty()) {
            return null;
        }
        E value = head.next.value;
        head.next = head.next.next;
        if (head.next == head) {
            tail = head;
        }
        size--;
        return value;
    }

    /**
     * 从队列头获取值, 不移除
     * @return 如果队列非空返回对头值, 否则返回null
     */
    public E peak() {
        if (isEmpty()) {
            return null;
        }
        return head.next.value;
    }

    /**
     * 检查队列是否为空
     * @return 空返回true, 否则返回false
     */
    public boolean isEmpty() {
        return head == tail;
    }

    /**
     * 检查队列是否为满
     * @return 满返回true, 否则返回false
     */
    public boolean isFull(){
        return size == capacity;
    }
}
